package com.itic.appbase.applications.sys.user.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.applications.sys.relation.persistence.dao.UserRoleDao;
import com.itic.appbase.applications.sys.relation.persistence.model.UserRole;
import com.itic.appbase.applications.sys.tixianlog.persistence.dao.TixianLogDao;
import com.itic.appbase.applications.sys.tixianlog.persistence.model.TixianLog;
import com.itic.appbase.applications.sys.user.persistence.dao.SysUserDao;
import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.applications.sys.user.persistence.model.SysUserExample;
import com.itic.appbase.applications.sys.user.persistence.model.SysUserParamVo;
import com.itic.appbase.applications.sys.useraccount.persistence.dao.UserAccountDao;
import com.itic.appbase.applications.sys.useraccount.persistence.model.UserAccount;
import com.itic.appbase.applications.sys.useraccount.persistence.model.UserAccountExample;
import com.itic.appbase.applications.sys.useraccount.persistence.model.UserAccountExample.Criteria;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.MD5Helper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;

@Service
@Transactional
public class SysUserService
        extends CrudService<SysUserDao, SysUser, SysUserExample> {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private TixianLogDao tixianLogDao;
    @Autowired
    private UserAccountDao userAccountDao;
    
    private static final String RESET_PWD = "123456";
    
    private static final String ORG_CODE = "0";

    /**
     * 添加用户信息
     * 
     * @param sysUser 用户信息
     * @param roleList 角色列表
     * @return
     */
    public String addUser(SysUser sysUser, List<UserRole> roleList) {
        String result = super.add(sysUser);
        if (SUCCESS.equals(result)) {
            for (UserRole userRole : roleList) {
                this.initDefalutFields(userRole); // 初始化6个必填字段
                int code = userRoleDao.insert(userRole);
                if (code < 1) {
                    result = FAILED;
                }
            }
        }
        return result;
    }

    /**
     * 删除用户信息
     * 
     * @param sysUser 用户信息
     * @param example 用户example
     * @param userIdList 用户id集合
     * @return
     */
    public String deleteUser(SysUser sysUser, SysUserExample example, List<String> userIdList) {
        String result = FAILED;
        int code = sysUserDao.updateByExampleSelective(sysUser, example); // 逻辑删除用户
        if (code > 0) {
            code = userRoleDao.deleteRoleByUserIds(userIdList); // 根据用户id物理删除用户角色关系
            if (code < 0) {
                result = FAILED;
            }
            result = SUCCESS;
        }
        return result;
    }

    /**
     * 用户角色分配
     * 
     * @param roleIds userRoleList
     * @return
     */
    public String roleAssign(String userId, List<UserRole> userRoleList) {
        String result = FAILED;
        // 先删除最初分配的角色
        int code = userRoleDao.deleteRoleByUserId(userId); // 物理删除成功标志为code>=0
       
        if (code >= 0) {
            for (UserRole userRole : userRoleList) {
                this.initDefalutFields(userRole); // 初始化6个必填字段
                code = userRoleDao.insert(userRole);
                if (code < 1) {
                    result = FAILED;
                }
            }
            result = SUCCESS;
        }

        return result;
    }

    /**
     * 重置密码
     * 
     * @param userList 用户list
     */
    public String resetPwd(String resetPwd, List<SysUser> userList) {
        String result = SUCCESS;
        for (SysUser sysUser : userList) {
            sysUser.setPassword(MD5Helper.md5DoubleSalt(resetPwd, sysUser.getUsername()));
            sysUser.setUpdateTime(new Date());
            int code = sysUserDao.updateByPrimaryKeySelective(sysUser);
            if (code < 1) {
                result = FAILED;
            }
        }
        return result;
    }

    /**
     * 根据用户TOKEN,设备信息获得用户信息
     * @param token
     * @param device
     * @return
     */
	public SysUser getUserByTokenAndDevice(String token, String device) {
		SysUserParamVo paramVo = new SysUserParamVo();
		paramVo.setToken(token);
		paramVo.setDevice(device);
		paramVo.setNowTime(new Date());
		paramVo.setIsEffective(DBConst.TRUE);
		paramVo.setIsOffsite(DBConst.FALSE);
		return sysUserDao.getUserByTokenAndDevice(paramVo);
	}

	/**
	 * 根据手机号码获得用户
	 * @param mobile
	 * @return
	 */
	public SysUser getByPhone(String mobile) {
		SysUser user = null;
		SysUserExample example = new SysUserExample();
		com.itic.appbase.applications.sys.user.persistence.model.SysUserExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andMobileEqualTo(mobile);
		List<SysUser> list = sysUserDao.selectByExample(example);
		if( !list.isEmpty() ){
			user = list.get(0);
		}
		return user;
	}

	/**
	 * 注册用户
	 * @param phone
	 * @return
	 */
	public SysUser reg(String phone) {
		SysUser user = new SysUser();
		user.setMobile(phone);
		user.setIsVip(UserType.user.getType());
		user.setMsgTips(0);
		user.setMoney(0.00);
		user.setUsername(phone);
		user.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, user.getUsername()));
		user.setRealname(phone);
		user.setOrg(ORG_CODE);
		user.setIsUsable(DBConst.TRUE);
		this.initDefalutFields(user);
		sysUserDao.insert(user);
		return user;
	}
	
	/**
	 * 注册用户
	 * @param phone
	 * @return
	 */
	public SysUser reg(SysUser user) {
		user.setIsVip(UserType.user.getType());
		user.setMsgTips(0);
		user.setMoney(0.00);
		if( StringHelper.isBlank(user.getUsername())){
			user.setUsername(user.getMobile());
		}
		if( StringHelper.isBlank(user.getRealname())){
			user.setRealname(user.getMobile());
		}
		user.setPassword(MD5Helper.md5DoubleSalt(RESET_PWD, user.getUsername()));
		user.setOrg(ORG_CODE);
		user.setIsUsable(DBConst.TRUE);
		this.initDefalutFields(user);
		sysUserDao.insert(user);
		return user;
	}

	/**
	 * 用户提现
	 * @param user
	 * @param money
	 * @return
	 */
	public String tixianSubmit(SysUser user, String money,UserAccount account) {
		user.setMoney(user.getMoney()-Double.parseDouble(money));
		sysUserDao.updateByPrimaryKeySelective(user);
		TixianLog tixianLog = new TixianLog();
		this.initDefalutFields(tixianLog);
		tixianLog.setUserId(user.getId());
		tixianLog.setUserName(user.getUsername());
		tixianLog.setMoney(Double.parseDouble(money));
		tixianLog.setStatus("verify");
		tixianLog.setUserAccountId(account.getId());
		tixianLog.setAccountName(account.getAccountName());
		tixianLog.setAccountType(account.getAccountType());
		tixianLog.setAccountNum(account.getAccountNum());
		tixianLog.setOrderNum(RandomOrderNumHelper.getOrderNumber());
		tixianLogDao.insert(tixianLog);
		//添加提现记录信息
		return SUCCESS;
	}

	/**
	 * 获取用户账号信息
	 * @param user
	 * @return
	 */
	public List<UserAccount> getUserAccount(SysUser user) {
		UserAccountExample example = new UserAccountExample();
		example.setOrderByClause("UPDATE_TIME DESC");
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(user.getId());
		return userAccountDao.selectByExample(example);
	}

}